<template>
  <div class="change-phone">
    <el-breadcrumb class="page-title" separator="/">
      <el-breadcrumb-item :to="{ path: '/changePhone' }">{{$t('m.LoginMethods')}}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form ref="form" :rules="rules" :model="form" label-width="150px"
             class="login-method form-box container-padding">

      <!--<h3 style="padding-top:20px;">Facebook or Google</h3>-->
      <!--<div class="lines"></div>-->

      <el-form-item label="Facebook">
        <div id="fb-root"></div>
        <div v-if="facebookId">
          <el-button style="width: 100px!important" @click="deleteBindFacebook">Unbind</el-button>
          <span class="other-id">{{facebookName}}</span>
        </div>
        <el-button style="width: 100px!important" @click="faceBookLogin" v-show="!facebookId">Bind</el-button>
      </el-form-item>
      <!--<el-form-item label="Google">-->
        <!--<div v-if="googleId">-->
          <!--<el-button style="width: 100px!important" @click="deleteBindGoogle">Unbind</el-button>-->
          <!--<span class="other-id">{{googleName}}</span>-->
        <!--</div>-->
        <!--<div id="googleBtnBind" v-show="!googleId"></div>-->
      <!--</el-form-item>-->

      <!--new start-->

      <el-form-item :label="$t('m.Phone')" v-if="!form.orginPhone">
        <el-button @click="smsPhone">{{$t('m.Addphone')}}</el-button>
      </el-form-item>

      <el-form-item :label="$t('m.Phone')" v-if="form.orginPhone">
        <el-button @click="smsPhone">{{$t('m.Changephone')}}</el-button>
        <span style="margin-left: 10px">{{form.orginPhone}}</span>
      </el-form-item>


      <!--<el-form-item label="Email" v-if="!bindEmailForm.originEmail">-->
        <!--<el-button @click="onBindEmail">{{$t('m.Addemail')}}</el-button>-->
      <!--</el-form-item>-->


      <!--<el-form-item label="Email" v-if="bindEmailForm.originEmail">-->
        <!--<el-button @click="onChangeEmail">{{$t('m.Changeemail')}}</el-button>-->
        <!--<span style="margin-left: 10px">{{bindEmailForm.originEmail}}</span>-->
      <!--</el-form-item>-->

      <!--<el-form-item :label="$t('m.Password')" v-if="bindEmailForm.originEmail || form.orginPhone">-->
      <el-form-item :label="$t('m.Password')">
        <el-button @click="onChangePassword">{{$t('m.Password')}}</el-button>
      </el-form-item>

      <!--new end-->

      <!--设置密码 弃用-->
      <!--<el-form ref="formPassword" style="padding-left: 0px" v-if="!showBindPhone" :rules="rulespassword"-->
      <!--:model="setPasswordForm" label-width="200px"-->
      <!--class="login-method form-box container-padding">-->
      <!--<div class="setPassword">-->
      <!--<h3>Password</h3>-->

      <!--<div class="lines"></div>-->

      <!--<div class="changePhone">-->
      <!--<el-form-item label="Your current phone number">-->
      <!--<el-input v-model="form.orginPhone" :disabled="true"></el-input>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="Password" prop="newPassword">-->
      <!--<el-input v-model="form.newPassword"></el-input>-->
      <!--<span>At least 8 or more characters. At least 1 number.</span>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="Send SMS">-->
      <!--<el-button style="width: 100%" @click="sendPasswordSMS" :disabled="disableds">Send SMS password to my-->
      <!--phone <span-->
      <!--v-if="isSendMsgs">{{times + 's'}}</span></el-button>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="SMS Password" prop="password">-->
      <!--<el-input v-model="form.password"></el-input>-->
      <!--</el-form-item>-->

      <!--<el-form-item class="submit">-->
      <!--<el-button type="warning" @click="onSubmitPassword">Bind password</el-button>-->
      <!--</el-form-item>-->
      <!--</div>-->
      <!--</div>-->
      <!--</el-form>-->

      <!--修改手机号码-->
      <!--<el-dialog-->
        <!--:title="$t('m.Changephone')"-->
        <!--:visible.sync="changePhoneDialogShow"-->
        <!--width="30%"-->
        <!--:before-close="changePhonehandleClose">-->
        <!--<el-form ref="formChangePhone" :rules="rules" :model="form">-->
          <!--<el-form-item :label="$t('m.Yourcurrentphonenumber')">-->
            <!--<el-input v-model="form.orginPhone" :disabled="true"></el-input>-->
          <!--</el-form-item>-->

          <!--<el-form-item :label="$t('m.NewPhoneNumber')" prop="newPhone">-->
            <!--<el-input v-model="form.newPhone"></el-input>-->
          <!--</el-form-item>-->

          <!--<el-form-item :label="$t('m.SendSMS')">-->
            <!--<el-button style="width: 100%" @click="sendSMS('setPassword')" :disabled="disabled">{{$t('m.SendSMSpasswordtomynewphone')}}<span-->
                <!--v-if="isSendMsg">{{time + 's'}}</span></el-button>-->
          <!--</el-form-item>-->

          <!--<el-form-item :label="$t('m.SMSPassword')" prop="password">-->
            <!--<el-input v-model="form.password"></el-input>-->
          <!--</el-form-item>-->

          <!--&lt;!&ndash;<el-form-item class="submit">&ndash;&gt;-->
          <!--&lt;!&ndash;<el-button type="warning" @click="onSubmit">Change phone number</el-button>&ndash;&gt;-->
          <!--&lt;!&ndash;</el-form-item>&ndash;&gt;-->
        <!--</el-form>-->


        <!--<span slot="footer" class="dialog-footer">-->
             <!--<el-button @click="changePhonehandleClose">{{$t('m.Cancel')}}</el-button>-->
             <!--<el-button type="primary" @click="changePhoneSubmit">{{$t('m.Submit')}}</el-button>-->
        <!--</span>-->
      <!--</el-dialog>-->

      <!--绑定手机号码-->
      <!--<el-dialog-->
        <!--:title="$t('m.Addphonenumber')"-->
        <!--:visible.sync="newPhoneDialogShow"-->
        <!--width="30%"-->
        <!--:before-close="newPhonehandleClose">-->
        <!--<el-form ref="formBindPhone" :rules="rules" :model="form">-->
          <!--<el-form-item :label="$t('m.PhoneNumber')" prop="newPhone">-->
            <!--<el-input v-model="form.newPhone"></el-input>-->
          <!--</el-form-item>-->

          <!--<el-form-item :label="$t('m.Password')" prop="newPassword">-->
            <!--<el-input type="password" v-model="form.newPassword"></el-input>-->
            <!--<span>{{$t('m.passwordRep')}}</span>-->
          <!--</el-form-item>-->

          <!--<el-form-item>-->
            <!--<el-button style="width: 100%" @click="sendSMS" :disabled="disabled">{{$t('m.SendSMSpasswordtomyphone')}}<span-->
              <!--v-if="isSendMsg">{{time + 's'}}</span></el-button>-->
          <!--</el-form-item>-->

          <!--<el-form-item :label="$t('m.SMSPassword')" prop="password">-->
            <!--<el-input v-model="form.password"></el-input>-->
          <!--</el-form-item>-->

          <!--&lt;!&ndash;<el-form-item class="submit">&ndash;&gt;-->
          <!--&lt;!&ndash;<el-button type="warning" @click="onSubmit">Bind phone number</el-button>&ndash;&gt;-->
          <!--&lt;!&ndash;</el-form-item>&ndash;&gt;-->

        <!--</el-form>-->


        <!--<span slot="footer" class="dialog-footer">-->
             <!--<el-button @click="newPhonehandleClose">{{$t('m.Cancel')}}</el-button>-->
             <!--<el-button type="primary" @click="newPhoneDialogSubmit">{{$t('m.Submit')}}</el-button>-->
        <!--</span>-->
      <!--</el-dialog>-->

      <!--绑定邮箱-->
      <el-dialog
        :title="$t('m.Addemail')"
        :visible.sync="newEmailDialogShow"
        width="30%"
        :before-close="newEmailhandleClose">
        <el-form ref="formBindEmail" :rules="rulesWithEmail" :model="bindEmailForm">
          <el-form-item label="Email" prop="email">
            <el-input v-model="bindEmailForm.email"></el-input>
          </el-form-item>

          <el-form-item :label="$t('m.Password')" prop="password">
            <el-input type='password' v-model="bindEmailForm.password"></el-input>
          </el-form-item>

          <!--<el-form-item class="submit">-->
          <!--<el-button type="warning" @click="onSubmit">Send validation to my email</el-button>-->
          <!--</el-form-item>-->
        </el-form>

        <span slot="footer" class="dialog-footer">
             <el-button @click="newEmailhandleClose">{{$t('m.Cancel')}}</el-button>
             <el-button type="primary"
                        @click="submitEmailFormSubmit('formBindEmail')">{{$t('m.Sendvalidationtomyemail')}}</el-button>
        </span>
      </el-dialog>

      <!--改变邮箱-->
      <el-dialog
        :title="$t('m.Changeemail')"
        :visible.sync="changeEmailDialogShow"
        width="30%"
        :before-close="ChangeEmailhandleClose">
        <el-form ref="formChangeEmail" :rules="rulesWithEmail" :model="bindEmailForm">
          <el-form-item :label="$t('m.CurrentEmail')" prop="email">
            <el-input v-model="bindEmailForm.originEmail" disabled></el-input>
          </el-form-item>

          <el-form-item :label="$t('m.Password')" prop="password">
            <el-input type='password' v-model="bindEmailForm.password"></el-input>
          </el-form-item>

          <el-form-item :label="$t('m.NewEmail')" prop="email">
            <el-input v-model="bindEmailForm.email"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
             <el-button @click="ChangeEmailhandleClose">{{$t('m.Cancel')}}</el-button>
             <el-button type="primary"
                        @click="submitChangeEmailFormSubmit('formChangeEmail')">{{$t('m.Changeemail')}}</el-button>
        </span>
      </el-dialog>

      <!--邮箱绑定之后提示-->
      <el-dialog
        :title="$t('m.EmailConfirmation')"
        :visible.sync="dialogVisible"
        :before-close="emailConfirmationClose"
        width="25%">
        <span>{{$t('m.Checkyouremailinbox')}}</span>
        <div class="btootm" style="text-align: center; padding-top: 20px">
          <el-button type="primary" @click="emailConfirmationClose">{{$t('m.Close')}}</el-button>
        </div>
      </el-dialog>

      <!--修改密码-->
      <el-dialog
        :title="$t('m.Password')"
        :visible.sync="changePasswordDialogShow"
        width="30%"
        :before-close="changePasswordhandleClose">
        <el-form ref="formChangePasswordRef" :rules="rulesWithPassword" :model="formChangePassword">

          <!--<el-form-item :label="$t('m.Currentpassword')" prop="currentPassword">-->
            <!--<el-input type='password' v-model="formChangePassword.currentPassword"></el-input>-->
          <!--</el-form-item>-->

          <el-form-item :label="$t('m.NewPassword')" prop="newPassword">
            <el-input type='password' v-model="formChangePassword.newPassword"></el-input>
          </el-form-item>

          <el-form-item :label="$t('m.RetypeNewpassword')" prop="retypePassword">
            <el-input type='password' v-model="formChangePassword.retypePassword"></el-input>
          </el-form-item>

          <!--<elform-item v-if="bindEmailForm.originEmail || form.orginPhone">-->
            <!--<div class="tipsforget" style="margin-bottom: 20px">{{$t('m.Nopassowrdorforgotpassword')}}</div>-->
            <!--<el-button v-if="bindEmailForm.originEmail" @click="sendEmail">Email</el-button>-->
            <!--<el-button v-if="form.orginPhone" @click="jumpToresetPassword">SMS</el-button>-->
          <!--</elform-item>-->
        </el-form>


        <span slot="footer" class="dialog-footer">
             <el-button @click="changePasswordhandleClose">{{$t('m.Cancel')}}</el-button>
             <el-button type="primary" @click="changePasswordSubmit">{{$t('m.Submit')}}</el-button>
        </span>
      </el-dialog>
    </el-form>

  </div>
</template>

<script>
  import {
    updatePhone,
    developerManage,
    bindingGoogle,
    unBindingGoogle,
    bindingFacebook,
    unBindingFacebook,
    resetPassword,
    sendBindEmail,
    updatePassword,
    sendChangeEmail
  } from '../../api/apiNext'
  import { sendSmsUser, registerUserWithEmail, setUserInfoPhone} from '../../api/api'
  import qs from 'qs'

  export default {
    name: 'company',
    data () {
      return {
        form: {
          orginPhone: '',
          newPhone: '',
          password: '',
          newPassword: ''
        },
        setPasswordForm: {
          orginPhone: '',
          password: '',
          newPassword: ''
        },
        time: 60, // 发送验证码倒计时
        isSendMsg: false, // 是否可以点击发送验证码
        disabled: false,  // 按钮是否可以点击
        times: 60, // 发送验证码倒计时
        isSendMsgs: false, // 是否可以点击发送验证码
        disableds: false,  // 按钮是否可以点击
        rules: {
          newPhone: [
            {required: true, type: 'string', message: 'please enter new phone number', trigger: 'blur'}
          ],
          password: [
            {required: true, type: 'string', message: 'please enter code', trigger: 'blur'}
          ],
          newPassword: [{
            validator: (rule, value, callback) => {
              if(value != ''){
                if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                  callback(new Error('At least 8 or more characters and at least 1 number.'))
                } else {
                  callback()
                }
              }
            }, trigger: 'blur'
          }],
          // newPassword: [{
          //   validator: (rule, value, callback) => {
          //     if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
          //       callback(new Error('At least 8 or more characters and at least 1 number'))
          //     } else {
          //       callback()
          //     }
          //   }, trigger: 'blur'
          // },
          //   {required: true, message: 'Please enter password', trigger: 'blur'}
          // ],
        },
        rulespassword: {
          newPassword: [
            {required: true, type: 'string', message: 'please enter password', trigger: 'blur'}
          ],
          password: [
            {required: true, type: 'string', message: 'please enter code', trigger: 'blur'}
          ],
        },
        rulesWithEmail: {
          email: [
            {required: true, message: 'Please enter the mailbox address', trigger: 'change'},
            {type: 'email', message: 'Please enter the correct mailbox address', trigger: 'change'}
          ],
          // password: [
          //   {required: true, message: 'password is null'}
          //   ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$
          // ],
          password: [{
            validator: (rule, value, callback) => {
              if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                callback(new Error('At least 8 or more characters and at least 1 number'))
              } else {
                callback()
              }
            }, trigger: 'change'
          },
            {required: true, message: 'Please enter password', trigger: 'change'}],
          type: [
            {type: 'array', required: true, message: '"Terms & Conditions" mustbe checked', trigger: 'change'}
          ],
        },
        rulesWithPassword: {
          currentPassword: [{
            validator: (rule, value, callback) => {
              if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                callback(new Error('At least 8 or more characters and at least 1 number'))
              } else {
                callback()
              }
            }, trigger: 'change'
          },
            {required: true, message: 'Please enter password', trigger: 'change'}],
          newPassword: [{
            validator: (rule, value, callback) => {
              if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                callback(new Error('At least 8 or more characters and at least 1 number'))
              } else {
                callback()
              }
            }, trigger: 'change'
          },
            {required: true, message: 'Please enter password', trigger: 'change'}],
          retypePassword: [{
            validator: (rule, value, callback) => {
              if(!(this.formChangePassword.newPassword == this.formChangePassword.retypePassword)){
                callback('Inconsistent password input')
              }
              if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                callback(new Error('At least 8 or more characters and at least 1 number'))
              }else{
                callback()
              }
            }, trigger: 'change'
          },
            {required: true, message: 'Please enter password', trigger: 'change'}],
        },
        googleId: '',
        facebookId: '',
        googleName: '',
        facebookName: '',
        showBindPhone: true,
        changePhoneDialogShow: false, // 修改手机号码dialog
        newPhoneDialogShow: false,
        bindEmailForm: {
          originEmail: '',
          email: '',
          password: '',
        },
        newEmailDialogShow: false,
        dialogVisible: false,
        changePasswordDialogShow: false,
        formChangePassword: {
          currentPassword: '',
          newPassword: '',
          retypePassword: '',
        },
        changeEmailDialogShow: false,
      }
    },
    methods: {
      onSubmit () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let sendData = {
              'phoneNumber': this.form.newPhone,
              'code': this.form.password
            }
            sendData = qs.stringify(sendData)
            updatePhone(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }

              if (res.data.errorID === 0) {
                this.showToast(0)

                localStorage.setItem('account', this.form.newPhone)

                this.form.orginPhone = this.form.newPhone
                this.form.newPhone = ''
                this.form.password = ''

                // 刷新页面数据
                this.getCompanyMessage()

              } else {
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              console.log(error)
            })
          } else {
            return false
          }
        })
      },
      onSubmitPassword () {
        this.$refs.formPassword.validate((valid) => {
          if (valid) {
            let sendData = {
              'phone': this.setPasswordForm.orginPhone,
              'code': this.setPasswordForm.password,
              'password': this.setPasswordForm.newPassword,
              'zone': '+95'
            }
            sendData = qs.stringify(sendData)
            resetPassword(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }

              if (res.data.errorID === 0) {
                this.showToast(0)

                this.setPasswordForm.password = ''

                // 刷新页面数据
                this.getCompanyMessage()

              } else {
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              console.log(error)
            })
          } else {
            return false
          }
        })
      },
      // 发送手机短信
      sendSMS () {
        if (!this.form.newPhone) {
          this.$message.error('pelase enter phone number!')
          return
        }

        this.isSendMsg = true
        this.disabled = true
        var msgInterval = setInterval(() => {
          this.time--
          if (this.time === 0) {
            clearInterval(msgInterval)
            this.isSendMsg = false
            this.disabled = false
            this.time = 60
          }
        }, 1000)

        let sendPhoneNumber = this.form.newPhone.substring(1, this.form.newPhone.length)
        // 调用手机短信接口
        let data = {
          'phoneNumber': sendPhoneNumber,
          'zone': '+95'
        }
        let params = qs.stringify(data)
        let self = this
        sendSmsUser(params)
          .then(function (res) {
            if (res.data.errorID === 100004) {
              this.showToast(res.data.errorID)
              this.$router.push('/login')
              return
            }
            if (res.data) {
              var data = res.data
              if (data.errorID === 0) {
                self.showToast(data.errorID)
              } else {
                self.showToast(data.errorID)
              }
            }
          })
          .catch(function (error) {
            console.log(error)
            self.showToast(error.errorID)
          })
      },
      // 发送设置密码短信
      sendPasswordSMS () {
        this.isSendMsgs = true
        this.disableds = true
        var msgInterval = setInterval(() => {
          this.times--
          if (this.times === 0) {
            clearInterval(msgInterval)
            this.isSendMsgs = false
            this.disableds = false
            this.times = 60
          }
        }, 1000)

        // 调用手机短信接口
        let data = {
          'phoneNumber': this.setPasswordForm.orginPhone,
          'zone': '+95'
        }
        let params = qs.stringify(data)
        let self = this
        sendSmsUser(params)
          .then(function (res) {
            if (res.data.errorID === 100004) {
              this.showToast(res.data.errorID)
              this.$router.push('/login')
              return
            }
            if (res.data) {
              var data = res.data
              if (data.errorID === 0) {
                self.showToast(data.errorID)
              } else {
                self.showToast(data.errorID)
              }
            }
          })
          .catch(function (error) {
            console.log(error)
            self.showToast(error.errorID)
          })
      },
      // 谷歌登录成功后回调函数
      onSuccess (googleUser) {
        var googleId = googleUser.getBasicProfile().getId()
        var name = googleUser.getBasicProfile().getName()
        var email = googleUser.getBasicProfile().getEmail()

        let data = {
          'googleId': googleId,
          'googleName': name,
          'googleEmail': email
        }
        let params = qs.stringify(data)
        bindingGoogle(params).then((res) => {
          let data = res.data
          if (data.errorID === 0) {
            this.showToast(0)
            //  数据插入data
            this.googleId = googleId
            this.googleName = name

            this.getCompanyMessage()
          } else {
            this.showToast(data.errorID)
          }
        }).catch((e) => {
          this.showToast(data.errorID)
        })
      },
      // 谷歌登录失败回调函数
      onFailure (e) {
        this.$message.error('error')
      },
      // 谷歌绑定按钮初始化
      renderButton () {
        window.gapi.signin2.render('googleBtnBind', {
          'scope': 'profile email',
          'width': 100,
          'height': 40,
          'longtitle': true,
          'theme': 'dark',
          'onsuccess': this.onSuccess,
          'onfailure': this.onFailure
        })
      },
      // 解除绑定谷歌
      deleteBindGoogle () {
        unBindingGoogle({}).then((res) => {
          let data = res.data
          if (data.errorID === 0) {
            this.showToast(0)
            var auth2 = window.gapi.auth2.getAuthInstance()
            auth2.signOut()
            this.getCompanyMessage()
          } else {
            this.showToast(data.errorID)
          }
        }).catch((e) => {
          this.showToast(data.errorID)
        })
      },
      // FaceBook 登錄按鈕初始化
      faceBookInit () {
        window.fbAsyncInit = function () {
          window.FB.init({
            appId: '1876620675891782',
            autoLogAppEvents: true,
            xfbml: true,
            version: 'v2.11' //facebook登录版本
          })
        }
      },
      // 調用FaceBook登錄按鈕
      faceBookLogin () {
        window.FB.login((response) => {
          this.statusChangeCallback(response)
        }, {scope: 'public_profile'})
      },
      statusChangeCallback (response) {
        if (response.status === 'connected') {
          FB.api('/me?fields=name,token_for_business', (response) => { // /me为API指定的调用方法，用于获取登陆用户相关信息
            if (response.id) {
              this.loginWithFaceBookLast(response)
            } else {
              this.messageT('error', 'error,please try again later')
            }
          })
        }
      },
      loginWithFaceBookLast (response) {
        if (response) {
          var facebookId = response.id
          var name = response.name
          // var email = response.email
          let tokenForBusiness = response.token_for_business;
          let data = {
            'facebookId': facebookId,
            'facebookName': name,
            'tokenForBusiness': tokenForBusiness,
            // 'facebookEmail': email
          }
          let params = qs.stringify(data)

          // 调用绑定facebook的接口
          bindingFacebook(params).then((res) => {
            let data = res.data
            if (data.errorID === 0) {
              this.showToast(data.errorID)
              //  数据插入data
              this.facebookId = facebookId
              this.facebookName = name

              this.getCompanyMessage()
            } else {
              this.showToast(data.errorID)
            }
          }).catch((e) => {
            this.showToast(data.errorID)
          })
        }
      },
      //deleteBindFacebook  解除绑定facebook
      deleteBindFacebook () {
        unBindingFacebook({}).then((res) => {
          let data = res.data
          if (data.errorID === 0) {
            this.showToast(data.errorID)
            // 调用退出Facebook登录方法
            FB.logout(function (response) {
              // Person is now logged out
            })

            this.getCompanyMessage()
          }
        }).catch((e) => {
          this.showToast(data.errorID)
        })
      },
      // 发起请求公司信息
      getCompanyMessage () {
        this.form.orginPhone = localStorage.getItem('account')
        this.setPasswordForm.orginPhone = localStorage.getItem('account')
        let developerId = localStorage.getItem('developerId')
        developerManage(developerId).then((res) => {
          if (res.data.errorID === 100004) {
            this.showToast(res.data.errorID)
            this.$router.push('/login')
            return
          }
          let data = res.data.object

          // 判断手机号码是否已经绑定
          if (!data.account) {
            this.showBindPhone = true
          } else {
            this.showBindPhone = false
          }

          // 邮箱是否绑定 绑定赋值
          this.bindEmailForm.originEmail = data.accountEmail || ''

          if (data.googleId) {
            this.googleId = data.googleId
            this.googleName = data.googleName
          } else {
            this.googleId = ''
            // 初始化谷歌绑定按钮
            this.renderButton()
          }

          if (data.facebookId) {
            this.facebookId = data.facebookId
            this.facebookName = data.facebookName
          } else {
            this.facebookId = ''
            // 初始化facebook绑定按钮
            this.faceBookInit()
          }

        })
          .catch((error) => {
            console.log(error)
          })
      },
      // 绑定手机
      onBindPhone () {
        this.newPhoneDialogShow = true
      },
      // 更换手机号码
      onChangePhone () {
        this.changePhoneDialogShow = true
      },
      changePhonehandleClose () {
        this.changePhoneDialogShow = false
        this.form.newPhone = ''
        this.form.password = ''
      },
      changePhoneSubmit () {
        this.$refs.formChangePhone.validate((valid) => {
          if (valid) {
            let sendData = {
              'phoneNumber': this.form.newPhone,
              'code': this.form.password,
            }
            sendData = qs.stringify(sendData)
            updatePhone(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }

              if (res.data.errorID === 0) {
                this.showToast(0)

                localStorage.setItem('account', this.form.newPhone)

                this.form.orginPhone = this.form.newPhone
                this.form.newPhone = ''
                this.form.password = ''
                this.form.newPassword = ''
                this.changePhoneDialogShow = false

                // 刷新页面数据
                this.getCompanyMessage()

              } else {
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              console.log(error)
            })
          } else {
            return false
          }
        })
      },
      newPhonehandleClose () {
        this.newPhoneDialogShow = false
        this.form.newPhone = ''
        this.form.password = ''
        this.form.newPassword = ''
      },
      newPhoneDialogSubmit () {
        this.$refs.formBindPhone.validate((valid) => {
          if (valid) {
            let sendData = {
              'phoneNumber': this.form.newPhone,
              'code': this.form.password,
              'password': this.form.newPassword
            }
            sendData = qs.stringify(sendData)
            updatePhone(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }

              if (res.data.errorID === 0) {
                this.showToast(0)

                localStorage.setItem('account', this.form.newPhone)

                this.form.orginPhone = this.form.newPhone
                this.form.newPhone = ''
                this.form.password = ''
                this.form.newPassword = ''
                this.newPhoneDialogShow = false

                // 刷新页面数据
                this.getCompanyMessage()

              } else {
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              console.log(error)
            })
          } else {
            return false
          }
        })
      },
      onBindEmail () {
        this.newEmailDialogShow = true
      },
      submitEmailFormSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              'accountEmail': this.bindEmailForm.email,
              'password': this.bindEmailForm.password
            }
            let params = qs.stringify(data)
            this.loading = true
            sendBindEmail(params)
              .then((res) => {
                if (res.data) {
                  var data = res.data
                  if (data.errorID === 0) {
                    this.showToast(data.errorID)

                    this.$refs['formBindEmail'].resetFields()
                    // 清除表单
                    this.bindEmailForm = {
                      originEmail: '',
                      email: '',
                      password: '',
                    },

                      this.loading = false
                    this.newEmailDialogShow = false
                    setTimeout(() => {
                      this.dialogVisible = true
                    }, 1200)
                  } else {
                    this.loading = false
                    this.showToast(data.errorID)
                  }
                }
              })
              .catch((error) => {
                console.log(error)
                this.loading = false
                this.messageToastErr('error,please try again later')
              })
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      onChangeEmail () {
        this.changeEmailDialogShow = true
      },
      ChangeEmailhandleClose(){
        this.changeEmailDialogShow = false;
        this.$refs['formChangeEmail'].resetFields()
      },
      submitChangeEmailFormSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              'accountEmail': this.bindEmailForm.email,
              'password': this.bindEmailForm.password
            }
            let params = qs.stringify(data)
            this.loading = true
            sendChangeEmail(params)
              .then((res) => {
                if (res.data) {
                  var data = res.data
                  if (data.errorID === 0) {
                    this.showToast(data.errorID)

                    this.$refs['formChangeEmail'].resetFields()
                    // 清除表单
                    this.bindEmailForm = {
                      originEmail: '',
                      email: '',
                      password: '',
                    },

                      this.loading = false
                    this.changeEmailDialogShow = false
                    setTimeout(() => {
                      this.dialogVisible = true
                    }, 1200)
                  } else {
                    this.loading = false
                    this.showToast(data.errorID)
                  }
                }
              })
              .catch((error) => {
                console.log(error)
                this.loading = false
                this.messageToastErr('error,please try again later')
              })
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      newEmailhandleClose () {
        this.newEmailDialogShow = false
        this.bindEmailForm.originEmail = ''
        this.bindEmailForm.email = ''
        this.bindEmailForm.password = ''
        this.$refs['formBindEmail'].resetFields()
      },
      emailConfirmationClose () {
        this.dialogVisible = false
      },
      onChangePassword () {
        this.changePasswordDialogShow = true
      },
      changePasswordhandleClose () {
        this.changePasswordDialogShow = false
        this.$refs['formChangePasswordRef'].resetFields()
      },
      translateZTUnicode(str){
        if (!str) return false;
        return this.$translateLang(str, 'zawgyiTounicode')
      },
      changePasswordSubmit () {
        this.$refs['formChangePasswordRef'].validate((valid) => {
          if (valid) {

            if(!(this.formChangePassword.newPassword == this.formChangePassword.retypePassword)){
              this.showToast(210003)
              return
            }

            let sendData = {
              // 'oldPassword': this.formChangePassword.currentPassword,
              'newPassword': this.translateZTUnicode(this.formChangePassword.newPassword),
            }

            sendData = qs.stringify(sendData)

            updatePassword(sendData).then((res) => {
              if (res.data.errorID === 100004) {
                this.showToast(res.data.errorID)
                this.$router.push('/login')
                return
              }

              if (res.data.errorID === 0) {
                this.showToast(0)
                this.$refs['formChangePasswordRef'].resetFields()
                this.changePasswordDialogShow = false
                // 刷新页面数据
                this.getCompanyMessage()

              } else {
                this.showToast(res.data.errorID)
              }
            }).catch((error) => {
              console.log(error)
            })
          } else {
            return false
          }
        })
      },
      jumpToresetPassword(){
        this.$router.push('/resetPassword')
      },
      sendEmail(){
        this.$router.push('/resetPassword')
      },
      //新增 facebook SMS start
      initAccountKit() {
        const tag = document.createElement('script')
        tag.setAttribute(
          'src',
          `https://sdk.accountkit.com/en_US/sdk.js`
        )
        tag.setAttribute('id', 'account-kit')
        tag.setAttribute('type', 'text/javascript')
        tag.onload = () => {
          /* eslint-disable camelcase */
          window.AccountKit_OnInteractive = this.onLoad.bind(this)
          /* eslint-enable camelcase */
        }
        document.head.appendChild(tag)
      },
      onLoad() {
        window.AccountKit.init(
          {
            // appId: "269889663695520", // 测试版
            appId: "1876620675891782", // 正式版
            state: '1212111',
            version: "v1.1",
            display: "modal",
            fbAppEventsEnabled: true,
            debug: true,
          }
        )
      },
      // login callback
      loginCallback(response) {
        // console.log(response,'response')
        if (response.status === "PARTIALLY_AUTHENTICATED") {
          var code = response.code;
          // var csrf = response.state;
          // Send code to server to exchange for access token
          let data = {
            'code': code,
            // 'csrf': csrf
          }
          let params = qs.stringify(data)
          setUserInfoPhone(params).then((res) => {
            if (res.data.errorID === 100004) {
              this.showToast(res.data.errorID)
              this.$router.push('/login')
              return
            }

            if (res.data.errorID === 0) {
              this.showToast(0)

              localStorage.setItem('account', this.form.newPhone)

              // 刷新页面数据
              this.getCompanyMessage()

            } else {
              this.showToast(res.data.errorID)
            }
          }).catch((error) => {
            console.log(error)
            this.messageToastErr('No internet, please try again')
          })
        }
        else if (response.status === "NOT_AUTHENTICATED") {
          console.log('Not Authenticated')
        }
        else if (response.status === "BAD_PARAMS") {
          this.messageToastErr('Bad Params')
        }
      },
      // phone form submission handler
      smsPhone() {
        window.AccountKit.login('PHONE', {}, this.loginCallback)
      },
    },
    mounted () {
      this.getCompanyMessage()
      if (!window.AccountKit) {
        this.initAccountKit()
      }
    }
  }
</script>

<style>
  .form-box {
    padding-top: 30px;
    width: 600px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .change-phone .container-padding {
    padding: 30px 40px 0 40px;
  }

  .change-phone .container-padding h3 {
    margin: 0.8em 0;
  }

  .submit {
    text-align: left;
  }

  .other-id {
    margin-left: 10px;
  }

  #googleBtnBind {
    border-radius: 5px;
    overflow: hidden;
    width: 100px;
    border: 1px solid #d8dce5;
  }

  #googleBtnBind .abcRioButtonIcon {
    display: none !important;
  }

  #googleBtnBind .abcRioButtonBlue {
    background-color: #f4f4f4 !important;
  }

  #googleBtnBind .abcRioButtonContents span {
    display: none;
  }

  #googleBtnBind .abcRioButtonContents:before {
    content: 'Bind';
    color: #5a5e66;
    font-weight: bold;
  }

  .login-method .lines {
    padding: 10px 0 20px 0;
    border-top: 1px solid #d4d3d3;
  }

  .other-title {
    padding: 25px 0 25px 0;
  }

  .other-top {
    margin-top: -25px;
  }
</style>
